package lormi.meipin.interceptor;


import lormi.meipin.annotation.NotValidUser;
import lormi.meipin.annotation.RegClient;
import lormi.meipin.exception.LMException;
import lormi.meipin.service.IMemberService;
import lormi.meipin.service.ISystemInfoService;
import lormi.meipin.service.ITokenService;
import lormi.meipin.util.StringUtil;
import lormi.meipin.util.TEncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;


public class ApiInterceptor extends HandlerInterceptorAdapter{
	
	@Autowired
	private IMemberService memberService;

	@Autowired
	private ITokenService tokenService;

	@Autowired
	private ISystemInfoService systemInfoService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//获取URL对应的方法上的注解,判断是否需要验证用户的存在与否
		HandlerMethod mathod = (HandlerMethod) handler;
        NotValidUser noValidUser = mathod.getMethodAnnotation(NotValidUser.class);
        RegClient regClient = mathod.getMethodAnnotation(RegClient.class);
		//debug调试
		if ("true".equals(systemInfoService.getSystemValue("debug").getSvalue())) {
			debug(request);
		}
		if (regClient!=null){
            return true;
        }
        //验证sign
        checkSign(request);

        //不需要验证用户的接口
		if(noValidUser!=null){

		}else{//验证用户和token的正确性

            String token = request.getHeader("token");
            if (StringUtil.isNull(token)) {
                throw new LMException(100009);
            }
			if (StringUtil.isNull(request.getParameter("userid"))) {
				throw new LMException(150005);
			}
			Integer userId = Integer.valueOf(request.getParameter("userid"));
			if (StringUtil.isNull(request.getParameter("usertype"))) {
				throw new LMException(150004);
			}
			Integer userType = Integer.valueOf(request.getParameter("usertype"));
			if (memberService.getMember(userId,userType)==null) {
				throw new LMException(150012);
			}
			tokenService.checkTokenValid(userId, token);
		}
        return true;
	}

    /**
     * 校验sign
     * @param request
     * @return
     */
	public void checkSign(HttpServletRequest request) {

        String client = request.getHeader("client");
        if (StringUtil.isNull(client)){
            throw new LMException(200007);
        }
        String sign = request.getHeader("sign");
        if (StringUtil.isNull(sign)){
            throw new LMException(200008);
        }
        StringBuffer content = new StringBuffer();
		Enumeration<String> ns = request.getParameterNames();
        while(ns.hasMoreElements()){
            String key = ns.nextElement();
            String value = request.getParameter(key);
            content.append(key+"="+value);
        }
        String con = content.toString();
		System.out.println("content:"+con);
		String secret = systemInfoService.getSystemValue(client).getSvalue();
		String nSign;
        try {
            nSign = TEncryptUtil.enBase64(TEncryptUtil.enAES(TEncryptUtil.md5_32(con).toLowerCase(),secret));
			System.out.println(nSign);
		} catch (Exception e) {
            throw new LMException();
        }
        if (!sign.equals(nSign)){
            throw new LMException(200009);
        }
    }
	
	public void debug(HttpServletRequest request){
		//调试
		System.out.println("==================接口拦截器=======================");
		String api = request.getServletPath().substring(5);
		System.out.println("------------------"+api+"-----------");
		System.out.println("------------------header---start-----------");
		Enumeration<String> hs = request.getHeaderNames();
		while(hs.hasMoreElements()){
			String key = hs.nextElement();
			String value = request.getHeader(key);
			System.out.println("---------"+key+"--------"+value+"-------");
		}
		System.out.println("------------------header---end-------------");
		System.out.println("================================================");
		System.out.println("------------------param---start-----------");
		Enumeration<String> ns = request.getParameterNames();
		while(ns.hasMoreElements()){
			String key = ns.nextElement();
			String value = request.getParameter(key);
			System.out.println("---------"+key+"--------"+value+"-------");
		}
		System.out.println("------------------param---end-------------");
	}
		
}
